﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;
using System.Xml.Serialization;
using System.Text;

namespace RecipeMLSchema.Schema
{
	public static class SerializationHelper
	{
		public static void ToFile(object obj, string fileName)
		{
			using (StreamWriter streamWriter = new StreamWriter(fileName))
			{
				using (XmlWriter writer = new XmlTextWriter(streamWriter))
				{
					XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
					ns.Add("", "");
					new XmlSerializer(obj.GetType()).Serialize(writer, obj, ns);
					writer.Close();
				}
			}
		}

		public static T FromFile<T>(string fileName)
		{
			if (!File.Exists(fileName)) throw new ArgumentException("File does not exist: " + fileName);

			Type objectType = typeof(T);
			XmlRootAttribute xmlRoot = new XmlRootAttribute()
			{
				ElementName = objectType.Name,
				IsNullable = true,
			};
			XmlSerializer serializer = new XmlSerializer(objectType, xmlRoot);
			using (StreamReader streamReader = new StreamReader(fileName))
			{
				using (XmlReader reader = XmlReader.Create(streamReader))
				{
					return (T)serializer.Deserialize(reader);
				}
			}
		}
	}
}
